﻿using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CoreApp.Ali
{
    public static class SerializationExtensions
    {
        /// <summary>
        /// 将一个对象序列化生成为 Json 格式的字串。
        /// </summary>
        /// <param name="item"></param>
        /// <returns>Json 格式的字串。</returns>
        public static string ToJson(this object item)
        {
            string value = "";
            try
            {
                JsonSerializerSettings settings = new JsonSerializerSettings();
                settings.ContractResolver = new DefaultContractResolver();
                settings.MaxDepth = 3;
                value = JsonConvert.SerializeObject(item, settings);
            }
            catch (Exception e)
            {

            }
            return value;
        }

        /// <summary>
        /// 将 Json 格式的字串反序列化为指定的对象，转换失败时返回类型的默认值。
        /// </summary>
        /// <typeparam name="T">类型。</typeparam>
        /// <param name="json">Json 字串。</param>
        /// <returns>转换后的实例，转换失败时返回类型的默认值。</returns>
        public static T FromJson<T>(this string json)
        {

            try
            {
                return JsonConvert.DeserializeObject<T>(json);
            }
            catch
            {
                return default(T);
            }
        }

    }
}
